package com.zhengxyou.jetpackdemo.room;

import com.zhengxyou.jetpackdemo.MyApplication;
import com.zhengxyou.jetpackdemo.room.dao.UserDao;
import com.zhengxyou.jetpackdemo.room.dao.UserInfoDao;
import com.zhengxyou.jetpackdemo.room.databaseView.UserDetail;
import com.zhengxyou.jetpackdemo.room.entity.User;
import com.zhengxyou.jetpackdemo.room.entity.UserInfo;
import com.zhengxyou.jetpackdemo.room.typeConverter.Converters;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverters;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

@TypeConverters(value = {Converters.class})
@Database(entities = {User.class, UserInfo.class}, version = 1, views = {UserDetail.class}, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    private static final String DB_NAME = "testRoomDatabase";
    private static volatile AppDatabase mInstance;

    public static AppDatabase getInstance() {
        if (mInstance == null) {
            mInstance = create();
        }
        return mInstance;
    }

    private static AppDatabase create() {
        return Room.databaseBuilder(MyApplication.getGlobeContext(), AppDatabase.class, DB_NAME)
                .addMigrations(MIGRATION_1_2, MIGRATION_2_3)
                .build();
    }

    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE User "
                    + " ADD COLUMN age INTEGER NOT NULL DEFAULT(0)");
        }
    };
    private static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE User "
                    + " ADD COLUMN card_id varchar(50)");
        }
    };

    public abstract UserDao userDao();

    public abstract UserInfoDao userInfoDao();
}
